<?php
/**
 *Telegram @cocolive9 2023/9/25 16:12
 */


namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 会员接口
 */
class Ttpay extends Api
{


    public function getopenid(){

        $code  = $this->request->param('code');

        $url='https://developer.toutiao.com/api/apps/v2/jscode2session';
        $data=[
            'appid'=>'888',
            'secret'=>'888',
            'code'=>$code,
            //'anonymous_code'=>$anonymousCode,
        ];


        $res=$this->json_post($url,$data);


        var_dump($res);
        die;
    }

public function json_post($url, $data = [])
    {
        //$data=http_build_query($data);
        //$data=json_encode($data);
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }


    /**
     * 调起支付
     * @Author   Dc
     * @DateTime 2020-07-29T14:44:37+0800
     */
    public function pay(Request $request)
    {
        $openid  = $request->param('openid', 0);
        $orderNo = $request->param('orderNo', 0);

        $findOrder = Db::table('gc_order')->where(['orderNo' => $orderNo, 'openid' => $openid])->find();
        if (!$findOrder) {
            return self::err('订单不存在');
        }

        $findUser = Db::table('data_user')->where('openid', $openid)->find();
        if (!$findUser) {
            return self::err('用户不存在');
        }
        $tt_pay_app_id     = sysconf('wechat.dy_apppid');
        $tt_merchant_id    = sysconf('wechat.dy_mch_id');
        $tt_pay_secret_key = $app_secret = sysconf('wechat.dy_appsecret');
        $ip                = $this->getRealIp();
        $risk_info         = [
            'ip' => $ip,
        ];
        $orderInfo = [
            "app_id"       => $tt_pay_app_id,
            "sign_type"    => "MD5",
            "out_order_no" => $orderNo,
            "merchant_id"  => $tt_merchant_id,
            "timestamp"    => (string) time(),
            "product_code" => "pay",
            "payment_type" => "direct",
            "total_amount" => $findOrder['price'] * 100,
            "trade_type"   => "H5",
            "uid"          => $openid,
            "version"      => "2.0",
            "currency"     => "CNY",
            "subject"      => "格创课堂",
            "body"         => "支付测试",
            "trade_time"   => (string) $findOrder['create_at'],
            "valid_time"   => "300",
            "notify_url"   => "https://tp-pay.snssdk.com/cashdesk/test/paycallback",
            // "wx_url"       => "https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx25161122572189727ea14cfd1832451500&package=2746219290",
            // "wx_type"      => "MWEB",
            "alipay_url"   => $this->getAliParam($findOrder),
        ];

        $stringToBeSigned = $this->getSignContent($orderInfo, "UTF-8", $app_secret);
        $sign             = md5($stringToBeSigned);

        $orderInfo['risk_info'] = json_encode($risk_info);
        $orderInfo['sign']      = $sign;
        return self::res($orderInfo);

    }


    /**
     * 签名处理
     * @param $params
     * @param $charset
     * @return string
     */
    public function getSignContent($params, $charset = "", $app_secret)
    {
        ksort($params);
        $stringToBeSigned = "";
        $i                = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $charset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        $stringToBeSigned = $stringToBeSigned . $app_secret;
        unset($k, $v);
        return $stringToBeSigned;
    }

    /**
     * 校验$value是否非空
     * @param $value
     * @return  boolean;
     *  if not set ,return true;
     *  if is null , return true;
     **/
    public function checkEmpty($value)
    {
        if (!isset($value)) {
            return true;
        }

        if ($value === null) {
            return true;
        }

        if (trim($value) === "") {
            return true;
        }

        return false;
    }

    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    public function characet($data)
    {
        if (!empty($data)) {
            $data = mb_convert_encoding($data, "UTF-8", "auto");
        }
        return $data;
    }


}
